package com.xtravel.discovery.activity;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.astuetz.PagerSlidingTabStrip;
import com.lidroid.xutils.BitmapUtils;
import com.xtravel.R;
import com.xtravel.common.fragment.BaseFragment;
import com.xtravel.discovery.api.LiveRequest;
import com.xtravel.discovery.dto.CountryState;

public class DiscoveryFragment extends BaseFragment {
    private TextView captionTextView, livingBtn;
    private Context context;
    private View frameView;
    private LiveRecordsView currentView;
    private ViewPager viewPager;
    private List<LiveRecordsView> discoveryPagesList = new ArrayList<LiveRecordsView>();
    private List<CountryState> allSupportedStates = new ArrayList<>();
    private BitmapUtils bitmapUtils;
    private PagerSlidingTabStrip pagerSlidingTabStrip;
    private LiveRequest apiRequest = new LiveRequest();

    public DiscoveryFragment() {
        super(R.layout.discovery_main_fragment);
    }

    @Override
    public void onFragmentChange(boolean isChange) {
        if (!isChange && currentView != null) {
            currentView.refresh();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        frameView = super.onCreateView(inflater, container, savedInstanceState);
        this.context = getActivity();
        this.bitmapUtils = new BitmapUtils(getActivity());
        pagerSlidingTabStrip = (PagerSlidingTabStrip) frameView.findViewById(R.id.pager_tab_strips);
        initPagerSlider();
        captionTextView = (TextView) frameView.findViewById(R.id.textCaption);
        viewPager = (ViewPager) frameView.findViewById(R.id.discoveryPager);
        getSupportedStates();
        livingBtn = (TextView) frameView.findViewById(R.id.text_live);
        livingBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), CountryLiveItemsActivity.class);
                intent.putExtra("name", "正在直播");
                intent.putExtra("code", "");
                intent.putExtra("islive", true);
                context.startActivity(intent);
            }
        });
        return frameView;
    }

    private void initPagerSlider() {
        int density = (int) getResources().getDisplayMetrics().density;
        pagerSlidingTabStrip.setIndicatorColorResource(R.color.color_white);
        pagerSlidingTabStrip.setUnderlineColorResource(R.color.transparant);
        pagerSlidingTabStrip.setDividerColorResource(R.color.transparant);
        pagerSlidingTabStrip.setIndicatorHeight(2 * density);
        pagerSlidingTabStrip.setTextColorResource(R.color.color_white);
        pagerSlidingTabStrip.setTabPaddingLeftRight(8 * density);
    }

    private void initDataAdapters() {
        discoveryPagesList.clear();
        for (CountryState state : allSupportedStates) {
            discoveryPagesList.add(new LiveRecordsView(this.getActivity(), state, this.bitmapUtils));
        }

        viewPager.setAdapter(discoveryViewPagerAdapter);
        pagerSlidingTabStrip.setViewPager(viewPager);
        pagerSlidingTabStrip.setOnPageChangeListener(viewPagerChangeListener);
        viewPager.setCurrentItem(0);
        if (discoveryPagesList.size() > 0)
            currentView = discoveryPagesList.get(0);
    }

    private void getSupportedStates() {
        new AsyncTask<Long, Void, List<CountryState>>() {
            @Override
            protected List<CountryState> doInBackground(Long... params) {
                List<CountryState> states = apiRequest.getCountryStates();
                return states;
            }

            @Override
            protected void onPostExecute(List<CountryState> states) {
                super.onPostExecute(states);
                Message msg = new Message();
                msg.obj = states;
                handler.sendMessage(msg);
            }
        }.execute();
    }

    private void setMainCaptionText(CountryState state) {
        String caption = state.state;
        if ("全部".equals(state.state))
            caption = "看世界";

        captionTextView.setText(caption);
    }

    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            List<CountryState> states = (List<CountryState>) msg.obj;
            CountryState s = new CountryState();
            s.state = "全部";
            s.stateCode = "all";
            states.add(0, s);
            allSupportedStates.clear();
            allSupportedStates.addAll(states);
            initDataAdapters();
        }
    };

    private PagerAdapter discoveryViewPagerAdapter = new PagerAdapter() {
        @Override
        public int getCount() {
            return discoveryPagesList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == obj;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View item = discoveryPagesList.get(position);
            ((ViewPager) container).addView(item, 0);
            return item;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(discoveryPagesList.get(position));
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return allSupportedStates.get(position).state;
        }
    };

    private OnPageChangeListener viewPagerChangeListener = new OnPageChangeListener() {
        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int index) {
            //setMainCaptionText(allSupportedStates.get(index));
            currentView = discoveryPagesList.get(index);
        }
    };
}
